﻿namespace DoxyOutParser
{
	using System;
	using System.Collections.Generic;
	using System.Globalization;
	using System.IO;

	public class CygwinDoxygenOutputParser : IOutputParser
	{
		public List<OutputEntry> Parse(string outputFile, string filter)
		{
			List<OutputEntry> entryList = new List<OutputEntry>();
			try
			{
				// Using of StreamReader to parse the file
				StreamReader cycleStreamReader = new StreamReader(outputFile);
				string line = cycleStreamReader.ReadLine();
				string[] paramSeparators = { ":" };

				while (line != null)
				{
					if (line.Length == 0)
					{
						line = cycleStreamReader.ReadLine();
					}
					else
					{
						string nextLine = cycleStreamReader.ReadLine();

						if (nextLine != null)
						{
							if (nextLine.StartsWith("/", StringComparison.Ordinal) && nextLine.Contains("Warning"))
							{
								string[] entryData = line.Split(paramSeparators, 4, StringSplitOptions.RemoveEmptyEntries);
								OutputEntry newEntry = CreateDoxygenOutputEntryFromEntryData(entryData);

								if (filter.Length != 0)
								{
									if (newEntry.FileNameAndPath.ToString().Contains(filter))
									{
										entryList.Add(newEntry);
									}
								}
								else
								{
									entryList.Add(newEntry);
								}

								line = nextLine;
							}
							else
							{
								line += "\r\n" + nextLine;
							}
						}
						else
						{
							string[] entryData = line.Split(paramSeparators, 4, StringSplitOptions.RemoveEmptyEntries);
							OutputEntry newEntry = CreateDoxygenOutputEntryFromEntryData(entryData);
							if (filter.Length != 0)
							{
								if (newEntry.FileNameAndPath.ToString().Contains(filter))
								{
									entryList.Add(newEntry);
								}
							}
							else
							{
								entryList.Add(newEntry);
							}

							// Set line to null because nextLine has been seen null already
							line = null;
						}
					}
				}
			}
			catch
			{
				throw;
			}

			return entryList;
		}

		private static OutputEntry CreateDoxygenOutputEntryFromEntryData(string[] entryData)
		{
			OutputEntry newEntry = new OutputEntry();

			if (entryData.Length == 4)
			{
				newEntry.FileNameAndPath = entryData[0].Substring(10, 1).ToUpper(CultureInfo.InvariantCulture) + ":\\" + entryData[0].Substring(12).Replace("/", "\\");
				newEntry.Line = entryData[1];
				newEntry.MessageType = entryData[2];
				newEntry.MessageDetails = entryData[3];
			}
			else
			{
				// TODO launch an exception if entryData.Lenght is different of 4
			}

			return newEntry;
		}
	}
}
